package com.uzai.console.service.uzaichat.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.ImgBase64;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.device.DeviceInfoDto;
import com.uzai.console.dto.feign.uzaichat.UpdateUzaichatNotifyDto;
import com.uzai.console.dto.uzaichat.kefuclient.KefuClientQuery;
import com.uzai.console.dto.uzaichat.kefuuser.KefuUserCancelSuspendDto;
import com.uzai.console.dto.uzaichat.kefuuser.KefuUserIdDto;
import com.uzai.console.dto.uzaichat.kefuuser.KefuUserInfoDto;
import com.uzai.console.dto.uzaichat.kefuuser.KefuUserQuery;
import com.uzai.console.dto.uzaichat.kefuuser.KefuUserSuspendDto;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.DeviceGroupMapper;
import com.uzai.console.mapper.KefuClientMapper;
import com.uzai.console.mapper.KefuUserMapper;
import com.uzai.console.mapper.SysRoleMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaichatFeignService;
import com.uzai.console.service.sysmaterial.SysMaterialService;
import com.uzai.console.service.uzaichat.KefuUserService;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.sysmaterial.UploadFileVo;
import com.uzai.console.vo.uzaichat.kefuuser.KefuUserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年09月01日 19:26
 */
@Service
public class KefuUserServiceImpl implements KefuUserService {

    @Autowired
    private KefuUserMapper kefuUserMapper;
    @Autowired
    private KefuClientMapper kefuClientMapper;
    @Autowired
    private SysMaterialService sysMaterialService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private UzaichatFeignService uzaichatFeignService;
    @Autowired
    private DeviceGroupMapper deviceGroupMapper;

    /**
     * 分页查询客服账号列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param kefuUserQuery
     * @return null
     */
    public Page<KefuUserInfoVo> findKefuUserList(KefuUserQuery kefuUserQuery){
        //新建返回到页面的LIST对象
        List<KefuUserInfoVo> kefuUserInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<KefuUser> page = new Page<>();
        kefuUserQuery.convert(page);
        List<KefuUser> kefuUserList = kefuUserMapper.findByList(page, kefuUserQuery);

        if(kefuUserList != null){
            for (KefuUser kefuUser : kefuUserList){
                KefuUserInfoVo kefuUserInfoVo = new KefuUserInfoVo();
                BeanUtils.copyProperties(kefuUser, kefuUserInfoVo);
                //挂起转交客服账号
                if(kefuUser.getTransferId() != null){
                    KefuUser transerUser = kefuUserMapper.selectById(kefuUser.getTransferId(), kefuUserQuery.getMerId());
                    if(transerUser != null){
                        kefuUserInfoVo.setTransferUser(transerUser.getUser());
                    }
                }

                //角色名称
                if(kefuUser.getRoleId() != null){
                    SysRole sysRole = sysRoleMapper.selectById(kefuUser.getRoleId(), kefuUserQuery.getMerId());
                    if(sysRole != null){
                        kefuUserInfoVo.setRoleName(sysRole.getName());
                    }
                }

                KefuClientQuery kefuClientQuery = new KefuClientQuery();
                kefuClientQuery.setMerId(kefuUserQuery.getMerId());
                kefuClientQuery.setKefuUserId(kefuUser.getId());
                List<KefuClient> kefuClientList =  kefuClientMapper.findByList(kefuClientQuery);
                if(kefuClientList != null && kefuClientList.size() > 0){
                    //关联机器人列表
                    List<DeviceInfoVo> deviceInfoVoList = new ArrayList<>(); //个人微信
                    List<DeviceInfoVo> deviceWxworkInfoVoList = new ArrayList<>(); //企业微信
                    List<DeviceInfoVo> deviceWxpubInfoVoList = new ArrayList<>(); //公众号微信
                    for (KefuClient kefuClient : kefuClientList){
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(kefuClient.getDeviceUniqueId(), kefuClient.getDeviceType(), kefuClient.getMerId());
                        if(device != null){
                            DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                            BeanUtils.copyProperties(device,deviceInfoVo);
                            if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(kefuClient.getDeviceType())){//个微
                                deviceInfoVoList.add(deviceInfoVo);
                            }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(kefuClient.getDeviceType())){//企微
                                deviceWxworkInfoVoList.add(deviceInfoVo);
                            }else if(DeviceTypeEnum.WX_PUB.getKey().equals(kefuClient.getDeviceType())){//公众号
                                deviceWxpubInfoVoList.add(deviceInfoVo);
                            }
                        }
                    }
                    kefuUserInfoVo.setDeviceInfoVoList(deviceInfoVoList);
                    kefuUserInfoVo.setDeviceWxworkInfoVoList(deviceWxworkInfoVoList);
                    kefuUserInfoVo.setDeviceWxpubInfoVoList(deviceWxpubInfoVoList);
                }
                kefuUserInfoVoList.add(kefuUserInfoVo);
            }
        }
        //返回到页面分页对象
        Page<KefuUserInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(kefuUserInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询客服账号详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param kefuUserIdDto
     * @return null
     */
    public KefuUserInfoVo findKefuUserInfo(KefuUserIdDto kefuUserIdDto){
        if(kefuUserIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        //查询页面用户
        KefuUser kefuUser = kefuUserMapper.selectById(kefuUserIdDto.getId(), kefuUserIdDto.getMerId());

        if(kefuUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该客服账号不存在");
        }

        KefuUserInfoVo kefuUserInfoVo =  new KefuUserInfoVo();
        BeanUtils.copyProperties(kefuUser, kefuUserInfoVo);

        //挂起转交客服账号
        if(kefuUser.getTransferId() != null){
            KefuUser transerUser = kefuUserMapper.selectById(kefuUser.getTransferId(), kefuUserIdDto.getMerId());
            if(transerUser != null){
                kefuUserInfoVo.setTransferUser(transerUser.getUser());
            }
        }

        //角色名称
        if(kefuUser.getRoleId() != null){
            SysRole sysRole = sysRoleMapper.selectById(kefuUser.getRoleId(), kefuUserIdDto.getMerId());
            if(sysRole != null){
                kefuUserInfoVo.setRoleName(sysRole.getName());
            }
        }

        //关联机器人列表
        KefuClientQuery kefuClientQuery = new KefuClientQuery();
        kefuClientQuery.setMerId(kefuUser.getMerId());
        kefuClientQuery.setKefuUserId(kefuUser.getId());
        List<KefuClient> kefuClientList =  kefuClientMapper.findByList(kefuClientQuery);
        if(kefuClientList != null && kefuClientList.size() > 0){
            //关联机器人列表
            List<DeviceInfoVo> deviceInfoVoList = new ArrayList<>(); //个人微信
            List<DeviceInfoVo> deviceWxworkInfoVoList = new ArrayList<>(); //企业微信
            List<DeviceInfoVo> deviceWxpubInfoVoList = new ArrayList<>(); //公众号微信
            for (KefuClient kefuClient : kefuClientList){
                Device device = deviceService.findDeviceInfoByDeviceUniqueId(kefuClient.getDeviceUniqueId(), kefuClient.getDeviceType(), kefuClient.getMerId());
                if(device != null){
                    DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                    BeanUtils.copyProperties(device,deviceInfoVo);
                    deviceInfoVo.setDeviceType(kefuClient.getDeviceType());
                    //群信息
                    DeviceGroup deviceGroup = deviceGroupMapper.selectById(device.getGroupId(), device.getMerId());
                    if(deviceGroup != null){
                        deviceInfoVo.setGroupName(deviceGroup.getName());
                    }
                    if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(kefuClient.getDeviceType())){//个微
                        deviceInfoVoList.add(deviceInfoVo);
                    }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(kefuClient.getDeviceType())){//企微
                        deviceWxworkInfoVoList.add(deviceInfoVo);
                    }else if(DeviceTypeEnum.WX_PUB.getKey().equals(kefuClient.getDeviceType())){//公众号
                        deviceWxpubInfoVoList.add(deviceInfoVo);
                    }

                }
            }
            kefuUserInfoVo.setDeviceInfoVoList(deviceInfoVoList);
            kefuUserInfoVo.setDeviceWxworkInfoVoList(deviceWxworkInfoVoList);
            kefuUserInfoVo.setDeviceWxpubInfoVoList(deviceWxpubInfoVoList);
        }

        return kefuUserInfoVo;
    }

    /**
     * 添加客服账号
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param kefuUserInfoDto
     * @return null
     */
    @Transactional
    public void addKefuUser(KefuUserInfoDto kefuUserInfoDto){
        if(kefuUserInfoDto.getUser() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择客服账号");
        }


        if(StringUtils.isBlank(kefuUserInfoDto.getPwd())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入登录密码");
        }

        if(kefuUserInfoDto.getName().length() > 32){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "登录密码不能超过32位");
        }

        if(StringUtils.isBlank(kefuUserInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入客服姓名");
        }

        if(kefuUserInfoDto.getName().length() > 32){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "客户姓名长度不能超过32位");
        }

        if(kefuUserInfoDto.getRoleId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择角色");
        }

        SysRole sysRole = sysRoleMapper.selectById(kefuUserInfoDto.getRoleId(), kefuUserInfoDto.getMerId());
        if(sysRole == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该角色不存在");
        }

        //个微
        List<DeviceInfoDto> deviceInfoDtoList = kefuUserInfoDto.getDeviceInfoDtoList();
        if(deviceInfoDtoList != null && deviceInfoDtoList.size()  > 0){
            for (DeviceInfoDto deviceInfoDto : deviceInfoDtoList){
                if(deviceInfoDto.getDeviceUniqueId() == null || StringUtils.isBlank(deviceInfoDto.getDeviceType())){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "绑定机器人唯一id和类型不能为空");
                }
            }
        }
        //企微
        List<DeviceInfoDto> deviceWxworkInfoDtoList = kefuUserInfoDto.getDeviceWxworkInfoDtoList();
        if(deviceWxworkInfoDtoList != null && deviceWxworkInfoDtoList.size()  > 0){
            for (DeviceInfoDto deviceInfoDto : deviceWxworkInfoDtoList){
                if(deviceInfoDto.getDeviceUniqueId() == null || StringUtils.isBlank(deviceInfoDto.getDeviceType())){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "绑定机器人唯一id和类型不能为空");
                }
            }
        }

        //公众号
        List<DeviceInfoDto> deviceWxpubInfoDtoList = kefuUserInfoDto.getDeviceWxpubInfoDtoList();
        if(deviceWxpubInfoDtoList != null && deviceWxpubInfoDtoList.size()  > 0){
            for (DeviceInfoDto deviceInfoDto : deviceWxpubInfoDtoList){
                if(deviceInfoDto.getDeviceUniqueId() == null || StringUtils.isBlank(deviceInfoDto.getDeviceType())){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "绑定机器人唯一id和类型不能为空");
                }
            }
        }

        String headImg = kefuUserInfoDto.getHeadImg();
        if(StringUtils.isNotBlank(headImg)){
            headImg = headImg.substring(headImg.indexOf("base64,")+7);
            InputStream stream = ImgBase64.getFile(headImg);
            UploadFileVo uploadFileVo = sysMaterialService.upload(kefuUserInfoDto.getMerId(), stream, IdWorker.get32UUID());
            kefuUserInfoDto.setHeadImg(uploadFileVo.getPathUrl());
        }



        KefuUser kefuUser = kefuUserMapper.selectByUser(kefuUserInfoDto.getUser());
        if(kefuUser != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该客服账号已经存在");
        }

        kefuUser = new KefuUser();
        BeanUtils.copyProperties(kefuUserInfoDto, kefuUser);
        Integer now = DateUtil.getNowTime();
        kefuUser.setId(IdWorker.getId());
        kefuUser.setCreateTime(now);
        kefuUser.setStatus(1);//正常
        kefuUser.setUpdateTime(now);

        //验证头像，如果头像为空，则修改成默认头像
        if(StringUtils.isBlank(kefuUser.getHeadImg())){
            kefuUser.setHeadImg(Const.Uzaichat.HEAD_IMG_URL);
        }

        //保存客服账号
        kefuUserMapper.insertSelective(kefuUser);
        //保存绑定个微机器人
        if(deviceInfoDtoList != null && deviceInfoDtoList.size()  > 0) {
            for (DeviceInfoDto deviceInfoDto : deviceInfoDtoList) {
                deviceInfoDto.setMerId(kefuUserInfoDto.getMerId());
                //先删除
                kefuClientMapper.deleteByDeviceUniqueId(deviceInfoDto.getDeviceUniqueId(), kefuUserInfoDto.getMerId());
                //在添加
                KefuClient kefuClient = new KefuClient();
                kefuClient.setId(IdWorker.getId());
                kefuClient.setMerId(kefuUser.getMerId());
                kefuClient.setKefuUserId(kefuUser.getId());
                kefuClient.setDeviceUniqueId(deviceInfoDto.getDeviceUniqueId());
                kefuClient.setDeviceType(deviceInfoDto.getDeviceType());
                kefuClient.setCreateTime(now);
                kefuClient.setUpdateTime(now);
                kefuClientMapper.insertSelective(kefuClient);
            }
        }

        //保存绑定企微机器人
        if(deviceWxworkInfoDtoList != null && deviceWxworkInfoDtoList.size()  > 0) {
            for (DeviceInfoDto deviceInfoDto : deviceWxworkInfoDtoList) {
                deviceInfoDto.setMerId(kefuUserInfoDto.getMerId());
                //先删除
                kefuClientMapper.deleteByDeviceUniqueId(deviceInfoDto.getDeviceUniqueId(), kefuUserInfoDto.getMerId());
                //在添加
                KefuClient kefuClient = new KefuClient();
                kefuClient.setId(IdWorker.getId());
                kefuClient.setMerId(kefuUser.getMerId());
                kefuClient.setKefuUserId(kefuUser.getId());
                kefuClient.setDeviceUniqueId(deviceInfoDto.getDeviceUniqueId());
                kefuClient.setDeviceType(deviceInfoDto.getDeviceType());
                kefuClient.setCreateTime(now);
                kefuClient.setUpdateTime(now);
                kefuClientMapper.insertSelective(kefuClient);
            }
        }

        //保存绑定公众号机器人
        if(deviceWxpubInfoDtoList != null && deviceWxpubInfoDtoList.size()  > 0) {
            for (DeviceInfoDto deviceInfoDto : deviceWxpubInfoDtoList) {
                deviceInfoDto.setMerId(kefuUserInfoDto.getMerId());
                //先删除
                kefuClientMapper.deleteByDeviceUniqueId(deviceInfoDto.getDeviceUniqueId(), kefuUserInfoDto.getMerId());
                //在添加
                KefuClient kefuClient = new KefuClient();
                kefuClient.setId(IdWorker.getId());
                kefuClient.setMerId(kefuUser.getMerId());
                kefuClient.setKefuUserId(kefuUser.getId());
                kefuClient.setDeviceUniqueId(deviceInfoDto.getDeviceUniqueId());
                kefuClient.setDeviceType(deviceInfoDto.getDeviceType());
                kefuClient.setCreateTime(now);
                kefuClient.setUpdateTime(now);
                kefuClientMapper.insertSelective(kefuClient);
            }
        }

        //更新客服账号发送消息配置
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.KEFU_SEND_MSG_CONFIG.getKey(), kefuUser.getId()), sysRole.getMessageData());

        //客服信息缓存删除
        redisTemplate.delete(String.format(RedisCacheKeyEnum.REDIS_KEFU_INFO_ID.getKey(), kefuUser.getId()));

    }

    /**
     * 修改客服账号
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param kefuUserInfoDto
     * @return null
     */
    @Transactional
    public void updateKefuUser(KefuUserInfoDto kefuUserInfoDto){

        if(kefuUserInfoDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        if(StringUtils.isBlank(kefuUserInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入客服姓名");
        }

        if(kefuUserInfoDto.getRoleId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择账号角色");
        }

        SysRole sysRole = sysRoleMapper.selectById(kefuUserInfoDto.getRoleId(), kefuUserInfoDto.getMerId());
        if(sysRole == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该角色不存在");
        }

        //个微
        List<DeviceInfoDto> deviceInfoDtoList = kefuUserInfoDto.getDeviceInfoDtoList();
        if(deviceInfoDtoList != null || deviceInfoDtoList.size() > 0){
            for (DeviceInfoDto deviceInfoDto : deviceInfoDtoList){
                if(deviceInfoDto.getDeviceUniqueId() == null || StringUtils.isBlank(deviceInfoDto.getDeviceType())){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "绑定机器人唯一id和类型不能为空");
                }
            }
        }

        //企微
        List<DeviceInfoDto> deviceWxworkInfoDtoList = kefuUserInfoDto.getDeviceWxworkInfoDtoList();
        if(deviceWxworkInfoDtoList != null && deviceWxworkInfoDtoList.size()  > 0){
            for (DeviceInfoDto deviceInfoDto : deviceWxworkInfoDtoList){
                if(deviceInfoDto.getDeviceUniqueId() == null || StringUtils.isBlank(deviceInfoDto.getDeviceType())){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "绑定机器人唯一id和类型不能为空");
                }
            }
        }

        //公众号
        List<DeviceInfoDto> deviceWxpubInfoDtoList = kefuUserInfoDto.getDeviceWxpubInfoDtoList();
        if(deviceWxpubInfoDtoList != null && deviceWxpubInfoDtoList.size()  > 0){
            for (DeviceInfoDto deviceInfoDto : deviceWxpubInfoDtoList){
                if(deviceInfoDto.getDeviceUniqueId() == null || StringUtils.isBlank(deviceInfoDto.getDeviceType())){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "绑定机器人唯一id和类型不能为空");
                }
            }
        }

        KefuUser kefuUser = kefuUserMapper.selectById(kefuUserInfoDto.getId(), kefuUserInfoDto.getMerId());
        if(kefuUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该客服账号不存在");
        }

        String headImg = kefuUserInfoDto.getHeadImg();
        if(StringUtils.isBlank(headImg)){
            kefuUser.setHeadImg("");
        }else if(!headImg.equals(kefuUser.getHeadImg())){
            headImg = headImg.substring(headImg.indexOf("base64,")+7);
            InputStream stream = ImgBase64.getFile(headImg);
            UploadFileVo uploadFileVo = sysMaterialService.upload(kefuUserInfoDto.getMerId(), stream, IdWorker.get32UUID());
            kefuUser.setHeadImg(uploadFileVo.getPathUrl());
        }

        kefuUser.setName(kefuUserInfoDto.getName());
        kefuUser.setRoleId(kefuUserInfoDto.getRoleId());
        if(StringUtils.isNotBlank(kefuUserInfoDto.getPwd())){
            kefuUser.setPwd(kefuUserInfoDto.getPwd());
        }
        //修改客服账号
        Integer now  = DateUtil.getNowTime();
        kefuUser.setUpdateTime(now);

        //验证头像，如果头像为空，则修改成默认头像
        if(StringUtils.isBlank(kefuUser.getHeadImg())){
            kefuUser.setHeadImg(Const.Uzaichat.HEAD_IMG_URL);
        }

        kefuUser.setAuthtype(kefuUserInfoDto.getAuthtype());

        kefuUserMapper.updateById(kefuUser);

        //修改绑定机器人
        kefuClientMapper.deleteByKefuUserId(kefuUser.getId(), kefuUserInfoDto.getMerId());//先删除，在统一添加
        if(deviceInfoDtoList != null || deviceInfoDtoList.size() > 0) {
            for (DeviceInfoDto deviceInfoDto : deviceInfoDtoList) {
                deviceInfoDto.setMerId(kefuUserInfoDto.getMerId());
                //先删除
                kefuClientMapper.deleteByDeviceUniqueId(deviceInfoDto.getDeviceUniqueId(), kefuUserInfoDto.getMerId());
                //在添加
                KefuClient kefuClient = new KefuClient();
                kefuClient.setId(IdWorker.getId());
                kefuClient.setMerId(kefuUser.getMerId());
                kefuClient.setKefuUserId(kefuUser.getId());
                kefuClient.setDeviceUniqueId(deviceInfoDto.getDeviceUniqueId());
                kefuClient.setDeviceType(deviceInfoDto.getDeviceType());
                kefuClient.setCreateTime(now);
                kefuClient.setUpdateTime(now);
                kefuClientMapper.insertSelective(kefuClient);
            }
        }

        //修改绑定企微机器人
        if(deviceWxworkInfoDtoList != null && deviceWxworkInfoDtoList.size() > 0) {
            for (DeviceInfoDto deviceInfoDto : deviceWxworkInfoDtoList) {
                deviceInfoDto.setMerId(kefuUserInfoDto.getMerId());
                //先删除
                kefuClientMapper.deleteByDeviceUniqueId(deviceInfoDto.getDeviceUniqueId(), kefuUserInfoDto.getMerId());
                //在添加
                KefuClient kefuClient = new KefuClient();
                kefuClient.setId(IdWorker.getId());
                kefuClient.setMerId(kefuUser.getMerId());
                kefuClient.setKefuUserId(kefuUser.getId());
                kefuClient.setDeviceUniqueId(deviceInfoDto.getDeviceUniqueId());
                kefuClient.setDeviceType(deviceInfoDto.getDeviceType());
                kefuClient.setCreateTime(now);
                kefuClient.setUpdateTime(now);
                kefuClientMapper.insertSelective(kefuClient);
            }
        }

        //保存绑定公众号机器人
        if(deviceWxpubInfoDtoList != null && deviceWxpubInfoDtoList.size()  > 0) {
            for (DeviceInfoDto deviceInfoDto : deviceWxpubInfoDtoList) {
                deviceInfoDto.setMerId(kefuUserInfoDto.getMerId());
                //先删除
                kefuClientMapper.deleteByDeviceUniqueId(deviceInfoDto.getDeviceUniqueId(), kefuUserInfoDto.getMerId());
                //在添加
                KefuClient kefuClient = new KefuClient();
                kefuClient.setId(IdWorker.getId());
                kefuClient.setMerId(kefuUser.getMerId());
                kefuClient.setKefuUserId(kefuUser.getId());
                kefuClient.setDeviceUniqueId(deviceInfoDto.getDeviceUniqueId());
                kefuClient.setDeviceType(deviceInfoDto.getDeviceType());
                kefuClient.setCreateTime(now);
                kefuClient.setUpdateTime(now);
                kefuClientMapper.insertSelective(kefuClient);
            }
        }

        //客服信息缓存删除
        redisTemplate.delete(String.format(RedisCacheKeyEnum.REDIS_KEFU_INFO_ID.getKey(), kefuUser.getId()));

        //更新客服账号发送消息配置
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.KEFU_SEND_MSG_CONFIG.getKey(), kefuUser.getId()), sysRole.getMessageData());
    }

    /**
     * 删除客服账号
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param kefuUserIdDto
     * @return null
     */
    @Transactional
    public void deleteKefuUser(KefuUserIdDto kefuUserIdDto){

        if(kefuUserIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择id");
        }

        KefuUser kefuUser = kefuUserMapper.selectById(kefuUserIdDto.getId(), kefuUserIdDto.getMerId());
        if(kefuUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该账号不存在");
        }

        //删除绑定的机器人
        kefuClientMapper.deleteByKefuUserId(kefuUserIdDto.getId(), kefuUserIdDto.getMerId());

        //删除客服账号
        kefuUserMapper.deleteById(kefuUserIdDto.getId(), kefuUserIdDto.getMerId());

        //删除客服账号发送消息配置
        redisTemplate.delete(String.format(RedisCacheKeyEnum.KEFU_SEND_MSG_CONFIG.getKey(), kefuUser.getId()));

        //删除登录token缓存和账户和token关系缓存
        //从cookie中获取账户和token关系缓存
        Object tokenObject = redisTemplate.opsForValue().get(String.format(CacheKey.LOGIN_TOKEN_RELATION, kefuUserIdDto.getId()));
        if (tokenObject != null) {
            String token = tokenObject.toString();
            //删除token
            redisTemplate.delete(String.format(CacheKey.LOGIN_TOKEN, token));
            //删除账户和token关系
            redisTemplate.delete(String.format(CacheKey.LOGIN_TOKEN_RELATION, kefuUserIdDto.getId()));
        }
        //客服信息缓存删除
        redisTemplate.delete(String.format(RedisCacheKeyEnum.REDIS_KEFU_INFO_ID.getKey(), kefuUserIdDto.getId()));

    }

    /**
     * 挂起客服账号
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param kefuUserSuspendDto
     * @return null
     */
    @Transactional
    public void suspendKefuUser(KefuUserSuspendDto kefuUserSuspendDto){
        if(kefuUserSuspendDto.getId() == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择id");
        }

        KefuUser kefuUser = kefuUserMapper.selectById(kefuUserSuspendDto.getId(), kefuUserSuspendDto.getMerId());
        if(kefuUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号id不存在");
        }

        if(kefuUserSuspendDto.getTransferId() != null ){
            if(kefuUserSuspendDto.getId().longValue() == kefuUserSuspendDto.getTransferId().longValue()){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能转交给自己");
            }
            //查询该挂起账号状态
            KefuUser transerUser = kefuUserMapper.selectById(kefuUserSuspendDto.getTransferId(), kefuUserSuspendDto.getMerId());
            if (transerUser == null || transerUser.getStatus() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "转交账号不存在或者已经是挂起离线状态了");
            }
        }
        kefuUser.setStatus(0);//离线挂起状态
        kefuUser.setTransferId(kefuUserSuspendDto.getTransferId());
        kefuUserMapper.updateByIdSelective(kefuUser);

        //客服信息缓存删除
        redisTemplate.delete(String.format(RedisCacheKeyEnum.REDIS_KEFU_INFO_ID.getKey(), kefuUserSuspendDto.getId()));

        //通知悠聊系统
        UpdateUzaichatNotifyDto updateUzaichatNotifyDto = new UpdateUzaichatNotifyDto();
        updateUzaichatNotifyDto.setMerId(kefuUser.getMerId());
        updateUzaichatNotifyDto.setCsId(kefuUser.getId());
        uzaichatFeignService.updateNotify(updateUzaichatNotifyDto);
    }


    /**
     * 取消挂起客服账号
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param kefuUserCancelSuspendDto
     * @return null
     */
    public void cancelSuspendKefuUser(KefuUserCancelSuspendDto kefuUserCancelSuspendDto){
        if(kefuUserCancelSuspendDto.getId() == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择id");
        }

        KefuUser kefuUser = kefuUserMapper.selectById(kefuUserCancelSuspendDto.getId(), kefuUserCancelSuspendDto.getMerId());
        if (kefuUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号id不存在");
        }

        kefuUser.setStatus(1);//在线状态
        kefuUser.setTransferId(null);
        kefuUserMapper.updateById(kefuUser);

        //客服信息缓存删除
        redisTemplate.delete(String.format(RedisCacheKeyEnum.REDIS_KEFU_INFO_ID.getKey(), kefuUserCancelSuspendDto.getId()));

        //通知悠聊系统
        UpdateUzaichatNotifyDto updateUzaichatNotifyDto = new UpdateUzaichatNotifyDto();
        updateUzaichatNotifyDto.setMerId(kefuUser.getMerId());
        updateUzaichatNotifyDto.setCsId(kefuUser.getId());
        uzaichatFeignService.updateNotify(updateUzaichatNotifyDto);
    }

}
